import { useEffect, useState } from "react";
import { useRouter } from "next/router";

export default function UserDetails() {
  const router = useRouter();
  const { id } = router.query;
  const [user, setUser] = useState(null);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [roles, setRoles] = useState([]); // To hold available roles
  const [selectedRoles, setSelectedRoles] = useState([]); // To hold selected roles

  useEffect(() => {
    if (id) {
      const fetchUser = async () => {
        const res = await fetch(`/api/users?id=${id}`);
        const data = await res.json();
        setUser(data);
        setName(data.name);
        setEmail(data.email);
        setSelectedRoles(
          data.roles ? data.roles.map((role) => role.roleId) : [],
        );
      };

      const fetchRoles = async () => {
        const res = await fetch("/api/roles"); // Fetch available roles
        const data = await res.json();
        setRoles(data);
      };

      fetchUser();
      fetchRoles();
    }
  }, [id]);

  const handleUpdate = async (e) => {
    e.preventDefault();
    const res = await fetch(`/api/users?id=${id}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, email, roles: selectedRoles }), // Include selected roles
    });
    if (res.ok) {
      router.push("/users");
    }
  };

  const handleRoleChange = (roleId) => {
    setSelectedRoles((prev) => {
      if (prev.includes(roleId)) {
        return prev.filter((r) => r !== roleId); // Remove role if already selected
      } else {
        return [...prev, roleId]; // Add role if not selected
      }
    });
  };

  if (!user || roles.length === 0) return <div>加载中...</div>;

  return (
    <form onSubmit={handleUpdate} className="container mx-auto">
      <h1 className="text-2xl font-bold my-4">编辑用户</h1>
      <label>姓名</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        className="border border-gray-300 p-2 w-full mb-4"
        required
      />
      <label>邮箱</label>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        className="border border-gray-300 p-2 w-full mb-4"
        required
      />
      <h2 className="text-xl font-semibold my-4">角色设置</h2>
      <div className="mb-4">
        {roles.map((role) => (
          <div key={role.id} className="flex items-center">
            <input
              type="checkbox"
              id={role.id}
              checked={selectedRoles.includes(role.id)}
              onChange={() => handleRoleChange(role.id)}
              className="mr-2"
            />
            <label htmlFor={role.id}>{role.name}</label>{" "}
            {/* Assuming role has a name property */}
          </div>
        ))}
      </div>
      <button type="submit" className="bg-blue-500 text-white p-2 rounded">
        更新
      </button>
    </form>
  );
}
